package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teautil.models.RuntimeOptions;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.handler.WorkException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    private static final String KEY_PREFIX = RedisConstant.APP_LOGIN_PREFIX;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取手机登录验证码
     * 借助阿里云的短信服务，发送验证码到手机
     *
     * @param phone
     */
    @Override
    public void getCode(String phone) {
        // 验证手机号是否正确
        if (!StringUtils.hasText(phone)) {
            throw new WorkException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //从redis获取验证码
        String redisCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (redisCode != null) {
            //获取验证码的过期时间，用于提示用户多久后可以再次获取验证码
            Long expire = stringRedisTemplate.getExpire(KEY_PREFIX + phone, TimeUnit.MINUTES);

            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new WorkException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        // 生成验证码
        String code = createCode(6);

        // 发送验证码
        sendCode(phone, code);
        System.out.println("验证码为：" + code);

        // 将验证码存入redis
        stringRedisTemplate.opsForValue().set(KEY_PREFIX + phone, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    /**
     * 登录业务逻辑，要返回去token
     *
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //先进行数据校验
        //1.手机号不能为空
        //后续不建议这么叠if，容易被辞退，要学会用注解
        if (!StringUtils.hasText(phone)) {
            throw new WorkException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)) {
            throw new WorkException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.验证码用户是否存在
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        if (userInfo == null) {
            //如果用户不存在，就注册新的用户
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户" + phone.substring(phone.length() - 8));
            userInfoService.save(userInfo);
        }
        //3.验证码是否正确
        String redisCode = stringRedisTemplate.opsForValue().get(KEY_PREFIX + phone);
        if (redisCode == null) {
            //如果验证码不存在，说明已经过期
            throw new WorkException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        } else {
            if (!redisCode.equals(code)) {
                throw new WorkException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
            }
        }

        //4、判断用户状态
        if (userInfo.getStatus() != BaseStatus.ENABLE) {
            throw new WorkException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        //5.生成token
        String token = JwtUtil.createJWT(userInfo.getId(), userInfo.getPhone());
        return token;
    }


    /**
     * 生成验证码
     *
     * @param length
     * @return
     */
    public String createCode(Integer length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 发送短信验证码
     * 直接对着官方文档复制粘贴即可
     *
     * @param phone
     * @param code
     */
    public void sendCode(String phone, String code) {
        // 发送短信验证码
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")// 使用沙箱环境测试的模板CODE
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":" + "\"" + code + "\"" + "}");
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println("发送成功");
        } catch (Exception error) {
            throw new WorkException(ResultCodeEnum.SERVICE_ERROR);
        }
    }
}


